/*
 * @lc app=leetcode.cn id=59 lang=golang
 *
 * [59] 螺旋矩阵 II
 */

// @lc code=start
func generateMatrix(n int) [][]int {
	ret := [][]int{}
	if n == 0 {
		return ret
	}

	for i := 0; i < n; i++ {
		ret = append(ret, make([]int, n))
	}

	left := 0
	right := n - 1
	top := 0
	bottom := n - 1
	s := 1

	for left < right && top < bottom {
		for i := left; i < right; i++ {
			ret[top][i] = s
			s++
		}

		for i := top; i < bottom; i++ {
			ret[i][right] = s
			s++
		}

		for i := right; i > left; i-- {
			ret[bottom][i] = s
			s++
		}

		for i := bottom; i > top; i-- {
			ret[i][left] = s
			s++
		}

		top++
		bottom--
		left++
		right--
	}

	if left == right {
		ret[left][left] = s
	}

	return ret
}

// @lc code=end

